import { update_mo } from '$lib/utils';

import { invoke } from '@tauri-apps/api/core'

import { emit, listen } from '@tauri-apps/api/event';


let listenRecv: (() => void) | null = null;

export async function get_serial() {
    let get_serial_msg:string;
    get_serial_msg = await invoke('get_serial');
    return get_serial_msg;
};

export async function listen_serial(name: string, baud_rate: number) {
    let the_baud_rate:string = baud_rate.toString();
    let listen_serial_msg = await invoke('listen_serial', {name: name, baudRate: the_baud_rate})
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));

    // console.log(send_serial_msg);
    return listen_serial_msg;
}

export async function close_serialport() {
    if (listenRecv != null) {
        // listenRecv();
        listenRecv = null; // 清除 unlistenRecv 变量
    }
    let close_serialport_msg = await invoke('close_serialport', {})
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));

    // console.log(send_serial_msg);
    return close_serialport_msg;
}

export async function send_serial_emit(send_data: string) {
    emit('send', send_data);
};

export async function recv_serial_event() {
    listenRecv = await listen('recv', (event) => {update_mo(event.payload as string)});
};


export async function test() {
    let listen_serial_msg = await invoke('link_db')
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));
    console.log(listen_serial_msg);
}
